package com.demo.gulimall.product.controller;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.demo.common.utils.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.demo.gulimall.product.entity.PmsCategoryEntity;
import com.demo.gulimall.product.service.PmsCategoryService;
import com.demo.common.utils.PageUtils;
import com.demo.common.utils.R;


/**
 * 商品三级分类
 *
 * @author ÁõÏþ·å
 * @email lxf@gmail.com
 * @date 2020-12-15 23:38:28
 */
@RestController
@RequestMapping("product/pmscategory")
public class PmsCategoryController {
    @Autowired
    private PmsCategoryService pmsCategoryService;
    @Autowired
    private BaseMapper<PmsCategoryEntity> baseMapper;

    /**
     * 列表
     */
    @RequestMapping("/list")
    //@RequiresPermissions("product:pmscategory:list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = pmsCategoryService.queryPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 获取产品分类的目录树结构
     *
     * @return
     */
    @RequestMapping("list/getTree")
    public R getTree() {
        QueryWrapper<PmsCategoryEntity> wrapper = new QueryWrapper<>();
        wrapper.ne("show_status", Constant.COMMON_ZERO);
        List<PmsCategoryEntity> pmsCategoryEntities = baseMapper.selectList(wrapper);
        List<PmsCategoryEntity> filterList = pmsCategoryEntities.stream()
                .filter(pmsCategoryEntity -> pmsCategoryEntity.getParentCid() == 0)
                .map(category -> {
                    category.setChildren(getChildRen(category, pmsCategoryEntities));
                    return category;
                }).sorted(Comparator.comparingInt(PmsCategoryEntity::getSort)).collect(Collectors.toList());
        return R.ok().put("tree", filterList);
    }

    /**
     * 获取子分类，递归方式
     *
     * @param category
     * @return
     */
    private List<PmsCategoryEntity> getChildRen(PmsCategoryEntity category, List<PmsCategoryEntity> pmsCategoryEntities) {
        return pmsCategoryEntities.stream().filter(pmsCategoryEntity -> pmsCategoryEntity.getParentCid().equals(category.getCatId()))
                .map(pmsCategoryEntity -> {
                    pmsCategoryEntity.setChildren(getChildRen(pmsCategoryEntity, pmsCategoryEntities));
                    return pmsCategoryEntity;
                })
                .sorted(Comparator.comparingInt(PmsCategoryEntity::getSort))
                .collect(Collectors.toList());
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{catId}")
    //@RequiresPermissions("product:pmscategory:info")
    public R info(@PathVariable("catId") Long catId) {
        PmsCategoryEntity pmsCategory = pmsCategoryService.getById(catId);

        return R.ok().put("pmsCategory", pmsCategory);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    //@RequiresPermissions("product:pmscategory:save")
    public R save(@RequestBody PmsCategoryEntity pmsCategory) {
        String checkErro = checkParam(pmsCategory, Constant.SAVE);
        if (StrUtil.isNotEmpty(checkErro)) {
            return R.error(checkErro);
        }
        pmsCategoryService.save(pmsCategory);
        return R.ok();
    }

    /**
     * 校验基本参数
     *
     * @param pmsCategory
     * @param operateType 操作类型
     * @return
     */
    private String checkParam(PmsCategoryEntity pmsCategory, String operateType) {
        if (pmsCategory == null) {
            return "参数为空";
        }
        if (StrUtil.isEmpty(pmsCategory.getName())) {
            return "请输入分类名称";
        }
        if (Constant.UPDATE.equals(operateType) && pmsCategory.getCatId() == null) {
            return "分类id为空";
        }
        if (pmsCategory.getParentCid() == null) {
            return "上级分类为空";
        }
        if (pmsCategory.getCatLevel() == null) {
            return "分类级别为空";
        }
        return null;
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    //@RequiresPermissions("product:pmscategory:update")
    public R update(@RequestBody PmsCategoryEntity pmsCategory) {
        String checkErro = checkParam(pmsCategory, Constant.UPDATE);
        if (StrUtil.isNotEmpty(checkErro)) {
            return R.error(checkErro);
        }
        pmsCategoryService.updateById(pmsCategory);
        return R.ok("更新成功");
    }

    /**
     * 批量修改
     */
    @RequestMapping("/update/sort")
    //@RequiresPermissions("product:pmscategory:update")
    public R updateBatch(@RequestBody PmsCategoryEntity[] pmsCategory) {
        pmsCategoryService.updateBatchById(Arrays.asList(pmsCategory));
        return R.ok("批量更新成功");
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    //@RequiresPermissions("product:pmscategory:delete")
    public R delete(@RequestBody Long[] catIds) {
        //判断当前节点下有没有子节点，有则不允许删除
        if (catIds == null || catIds.length == 0) {
            return R.error("参数为空");
        }
        List<PmsCategoryEntity> pmsCategoryEntities = pmsCategoryService.listByIds(Arrays.asList(catIds));
        if (CollectionUtil.isEmpty(pmsCategoryEntities)) {
            return R.error("未查询到产品分类");
        }
        if (pmsCategoryEntities.stream().anyMatch(pmsCategoryEntity -> CollectionUtil.isNotEmpty(pmsCategoryEntity.getChildren()))) {
            return R.error("含有子分类，不允许删除");
        }
        //逻辑删除分类
        pmsCategoryService.removeByIds(Arrays.asList(catIds));
        return R.ok("删除成功");
    }

}
